<?php
/**
 * This class is the virtual representative of an HTML form, elements can be added to it and removed
 * from it. It's __toString method generates the entire HTML form.
 *
 * @author Niels Janssen
 * @since 2008-07-08
 * @package Form
 */
class Form extends FormContainer {

	/**
	 * The location the form will submit to.
	 *
	 * @var String
	 */
	private $action = '';
	
	private $upload = false;
	
	/**
	 * The constructor of the Form class.
	 *
	 * @param String $action
	 */
	public function __construct( $method = 'post', $action = '', $properties = array() ) {
		$this->method = $method;
		$this->action = $action;
		$this->setProperties( $properties );
	}

	/**
	 * Lists all the errors in the form, format is element_id => error message.
	 *
	 * @param FormNode $element
	 */
	public function listAllErrors( $element = null ) {
		$errors = array();
		if( $element == null ) {
			$element = $this;
		}

		if( $element instanceof FormContainer && $element->hasChildren() && !$element->isValid() ) {
			foreach( $element->getChildren() as $child ) {
				$errors = array_merge( $errors, $this->listAllErrors( $child ) );
			}
		} elseif( $element instanceof FormElement ) {
			if( !$element->isValid() ) {
				$errorMessage = $element->getErrorMessage();
				if( substr( $element->getErrorMessage(), 0, 2 ) == '##' ){
					$errorMessage = __( $errorMessage );
				
				} else {
					//TODO: deze rare melding eruit gooien (en nooit meer dit soort dingen erin zetten)
					//$errorMessage = 'EEEK! GEEF HET EEN VERTALING OFZO';
				}

				$return = array( ( $element->getFormName() != '' ? $element->getFormName() . '_' : '' ) . $element->getName() => $errorMessage );
			}

			return isset( $return ) ? $return : array();
		}

		return $errors;
	}
	
	public function addChild(FormNode $child)
	{
		parent::addChild($child);
		
		if (!$this->upload && $child instanceof InputFile)
		{
			$this->upload = true;
		}
	}
	
	/**
	 * @see FormNode::__toString();
	 * @return String
	 */
	public function __toString( ) {
		$form = '<form method="' . $this->method . '" action="'.( $this->action != '' ? $this->action : '' ) . '" ' .( $this->getProperty('name') != '' ? 'name="'.$this->getProperty('name').'" id="form_'.$this->getProperty('name').'"' : '' );

		foreach ( $this->properties as $key => $value ) {
			if ( substr ( $key, 0, 5 ) == "html_" ) {
				$form .= ' '.substr ( $key, 5 ).'="'.$value.'"';
			}
		}
		
		// TODO: strpos vervangen, vragen aan Niels hoe het werkt.
		if (strpos($form, ' enctype="') === false && $this->upload)
		{
			$form .= ' enctype="multipart/form-data"';
		}
		
		$form .= '>';

		foreach( $this->children as $child ) {
			$form .= $child;
		}

		$form .= '</form>';

		return $form;
	}
}
